package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private RedisWorker redisWorker;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    @Override
    public Long secKillVoucher(Long voucherId) {
        // 查询优惠券信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        if (Objects.nonNull(seckillVoucher)) {
            Integer stock = seckillVoucher.getStock();
            LocalDateTime beginTime = seckillVoucher.getBeginTime();
            LocalDateTime endTime = seckillVoucher.getEndTime();
            // 判断秒杀是否开始
            if (beginTime.isAfter(LocalDateTime.now())) {
                throw new RuntimeException("秒杀尚未开始！");
            }
            // 判断秒杀是否结束
            if (endTime.isBefore(LocalDateTime.now())) {
                throw new RuntimeException("秒杀已结束！");
            }
            // 判断库存是否充足
            if (seckillVoucher.getStock() < 1) {
                throw new RuntimeException("商品优惠券库存不足！");
            }

            Long userId = UserHolder.getUser().getId();
            // 先获取锁，然后再进入方法，确保我的前一个订单会添加上,能先提交事务再释放锁
            //synchronized (userId.toString().intern()) {
            //    // 获得代理对象
            //    IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            //    // 默认是this,我们要实现事务需要proxy
            //    Long voucherOrder = proxy.createVoucherOrder(voucherId);
            //    return voucherOrder;
            //}

            // 分布式锁
            // 创建锁对象
            // 创建锁对象
            //SimpleReadIsLock lock = new SimpleReadIsLock("order:" + userId, stringRedisTemplate);
            RLock lock = redissonClient.getLock("order:" + userId);
            // 获取锁
            boolean hasLock = lock.tryLock();
            if (!hasLock) {
                // 获取锁失败
                throw new RuntimeException("请勿重复下单！");
            }
            try {
                IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
                Long voucherOrder = proxy.createVoucherOrder(voucherId);
                return voucherOrder;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        return null;
    }

    @Transactional
    public Long createVoucherOrder(Long voucherId) {
        // 查询订单是否存在
        Long userId = UserHolder.getUser().getId();
        if (query().eq("user_id", userId).eq("voucher_id", voucherId).count() > 0) {
            throw new RuntimeException("用户已经购买过该优惠券！");
        }
        // 扣减库存
        LambdaUpdateWrapper<SeckillVoucher> updateWrapper = Wrappers.lambdaUpdate(SeckillVoucher.class)
                .setSql("stock = stock - 1")
                .eq(SeckillVoucher::getVoucherId, voucherId)
                .gt(SeckillVoucher::getStock, 0);
        //.set(SeckillVoucher::getStock, stock - 1);
        boolean success = seckillVoucherService.update(updateWrapper);
        if (!success) {
            throw new RuntimeException("商品优惠券库存不足！");
        }
        // 新建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 生成订单id
        long orderId = redisWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 获取用户id
        voucherOrder.setUserId(userId);
        // 获取优惠券id
        voucherOrder.setVoucherId(voucherId);
        // 保存订单信息
        this.save(voucherOrder);
        // 返回订单id
        return orderId;
    }
}
